/**
 * Sub-Agents API Routes
 * 
 * RESTful API endpoints for managing sub-agents
 */

import { Hono } from 'hono';
import { getSubAgentManager } from '@/subagents';
import type { SubAgentConfig } from '@/subagents/subagent-manager';
import type { ApiResponse } from '@/types';
import { logger } from '@/utils/logger';

const app = new Hono();

/**
 * GET /api/subagents
 * 
 * List all registered sub-agents
 */
app.get('/', (c) => {
  try {
    const manager = getSubAgentManager();
    const subagents = manager.getAllSubAgents();
    const stats = manager.getStats();

    const response: ApiResponse = {
      success: true,
      data: {
        subagents,
        stats,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to list sub-agents', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'LIST_SUBAGENTS_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * GET /api/subagents/:id
 * 
 * Get a specific sub-agent by ID
 */
app.get('/:id', (c) => {
  try {
    const id = c.req.param('id');
    const manager = getSubAgentManager();
    const subagent = manager.getSubAgent(id);

    if (!subagent) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'SUBAGENT_NOT_FOUND',
          message: `Sub-agent with ID '${id}' not found`,
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 404);
    }

    const response: ApiResponse = {
      success: true,
      data: subagent,
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to get sub-agent', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'GET_SUBAGENT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * POST /api/subagents
 * 
 * Register a new sub-agent
 */
app.post('/', async (c) => {
  try {
    const config = await c.req.json<SubAgentConfig>();

    // Validate required fields
    if (!config.id || !config.name || !config.description || !config.prompt) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_CONFIG',
          message: 'Missing required fields: id, name, description, prompt',
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 400);
    }

    // Register the sub-agent
    const manager = getSubAgentManager();
    manager.registerSubAgent(config);

    const response: ApiResponse = {
      success: true,
      data: {
        id: config.id,
        message: `Sub-agent '${config.name}' registered successfully`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 201);
  } catch (error) {
    logger.error('Failed to register sub-agent', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'REGISTER_SUBAGENT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * PUT /api/subagents/:id
 * 
 * Update an existing sub-agent
 */
app.put('/:id', async (c) => {
  try {
    const id = c.req.param('id');
    const updates = await c.req.json<Partial<SubAgentConfig>>();

    const manager = getSubAgentManager();
    const success = manager.updateSubAgent(id, updates);

    if (!success) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'UPDATE_FAILED',
          message: `Failed to update sub-agent '${id}'. It may not exist or is a builtin sub-agent.`,
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 400);
    }

    const updatedAgent = manager.getSubAgent(id);

    const response: ApiResponse = {
      success: true,
      data: updatedAgent,
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to update sub-agent', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'UPDATE_SUBAGENT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * DELETE /api/subagents/:id
 * 
 * Remove a sub-agent
 */
app.delete('/:id', (c) => {
  try {
    const id = c.req.param('id');
    const manager = getSubAgentManager();
    const success = manager.removeSubAgent(id);

    if (!success) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'DELETE_FAILED',
          message: `Failed to delete sub-agent '${id}'. It may not exist or is a builtin sub-agent.`,
        },
        timestamp: new Date().toISOString(),
      };

      return c.json(response, 400);
    }

    const response: ApiResponse = {
      success: true,
      data: {
        id,
        message: `Sub-agent '${id}' deleted successfully`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to delete sub-agent', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'DELETE_SUBAGENT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * GET /api/subagents/config/sdk
 * 
 * Get SDK-compatible agents configuration
 * This returns the format expected by Claude Agent SDK's `agents` parameter
 */
app.get('/config/sdk', (c) => {
  try {
    const manager = getSubAgentManager();
    const config = manager.getAgentsConfig();

    const response: ApiResponse = {
      success: true,
      data: {
        agents: config,
        count: Object.keys(config).length,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to get SDK config', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'GET_SDK_CONFIG_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * POST /api/subagents/import
 * 
 * Import sub-agents from JSON configuration
 */
app.post('/import', async (c) => {
  try {
    const body = await c.req.json<{
      configs: SubAgentConfig[];
      overwrite?: boolean;
    }>();

    const manager = getSubAgentManager();
    const result = manager.importConfig(body.configs, body.overwrite);

    const response: ApiResponse = {
      success: result.errors.length === 0,
      data: result,
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to import sub-agents', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'IMPORT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * GET /api/subagents/export
 * 
 * Export all sub-agents configuration
 */
app.get('/export', (c) => {
  try {
    const manager = getSubAgentManager();
    const configs = manager.exportConfig();

    const response: ApiResponse = {
      success: true,
      data: {
        configs,
        count: configs.length,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to export sub-agents', error);
    
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'EXPORT_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
        details: error,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

export default app;

